package service

import (
	"context"
	"github.com/spf13/cast"
	"nearby/biz/common"
	"nearby/biz/dal/db/po"
	"nearby/biz/dal/db/repo"
	domainService "nearby/biz/domain/service"
	"nearby/biz/model"
)

type DeleteCommentService struct {
}

func (ss *DeleteCommentService) Execute(ctx context.Context, req *model.DeleteCommentRequest) (*model.DeleteCommentResponse, error) {
	// 1 权限校验
	user := common.GetUser(ctx)
	commentRepo := repo.NewCommentRepo(ctx)
	momentPo, err := commentRepo.GetComment(ctx, cast.ToInt64(req.CommentID))
	if err != nil {
		return nil, common.NewBizErr(common.EvilViewErrCode, "查询数据库失败", err)
	}
	if momentPo.UserID != user.UserID {
		return nil, common.NewBizErr(common.EvilViewErrCode, "删除的过程中好像有点问题", err)
	}

	// 2 删除
	err = commentRepo.DeleteMoment(ctx, momentPo)
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "删除动态失败", err)
	}

	// 3
	_ = ss.SyncCommentCount(ctx, momentPo)

	return &model.DeleteCommentResponse{
		Meta: common.MetaOk,
	}, nil
}

func (ss *DeleteCommentService) SyncCommentCount(ctx context.Context, po *po.Comment) error {
	commentDomainService := domainService.CommentService{}
	commentEntity, _ := commentDomainService.ToCommentEntity(po)
	return commentEntity.SyncCnt(ctx, -1)
}
